<template>
  <div class="changeMail">
    <HeaderTop :title="titleFonts"></HeaderTop>
    <div class="">
      <div class="reminds-fonts">*为提升您账号资金安全，涉及金额相关的操作均需要使用支付密码。</div>
      <div class="input-area">
        <div class="input-box">
          <van-field v-model="newPassword" type="digit" maxlength='6' label="新密码：" placeholder='请设置6位数字密码'/>
          <van-field v-model="confirmPassword" type="digit" maxlength='6' label="确认密码："
                     placeholder='请再次确认6位数字密码'/>
          <div v-show="newPassword && confirmPassword && newPassword!==confirmPassword" class="password-error">
            两次输入的密码不一致，请核对后重新输入。
          </div>
          <van-popup v-model="showPicker" position="bottom">
            <van-picker show-toolbar title="请选择一个验证方式" :columns="columns" :default-index="0" @confirm="(value, index)=>{
              verifyMode = value
              showPicker = false
              if(value==='手机验证'){
                deviceNumber = virtualInfo.phone
              }else if(value==='邮箱验证'){
                 deviceNumber = virtualInfo.email
              }
            }" @cancel="showPicker = false"/>
          </van-popup>
          <van-cell v-if="userData.paypassword" is-link @click="showPicker=true" title="验证方式："
                    :value="verifyMode ? verifyMode+deviceNumber :'请选择一个验证方式'"></van-cell>
          <div v-show="verifyMode" class="input-box2">
            <van-field v-model="vCode" type="digit" label="验证码：" maxlength='6' placeholder='请输入验证码'/>
            <van-button v-if='!isSending && verifyMode!=="谷歌验证"' class="code-btn" round color='#00459E' size="small" @click="getCode()">
              获取验证码
            </van-button>
            <van-button v-if='isSending' class="code-btn" round color='#00459E' size="small">{{ count }}s</van-button>
          </div>
        </div>
      </div>
      <van-button id="btnCover" color="#00459E" @click="confirm()" block round>提交</van-button>
      <div class="reminds-fonts">*支付密码请不要设置弱密码(如123456、666666、12341234..)，建议也不要与登录密码一致</div>
    </div>
    <van-loading id='pageLoading' v-if='isLoading' type="spinner" size="40" color="#1989fa"/>
  </div>
</template>

<script>
import HeaderTop from '../../components/top/top'
import {Toast} from 'vant'

export default {
  name: 'payPwdSet',
  components: {
    HeaderTop,
  },
  data() {
    return {
      userData: {},
      titleFonts: '设置支付密码',
      newPassword: '',
      confirmPassword: '',
      verifyMode: '',
      showPicker: false,
      columns: [],
      vCode: '',
      count: '',
      isSending: false,
      isLoading: false,
      deviceNumber:'',
      virtualInfo: {},
    }
  },
  mounted() {
    this.userData = JSON.parse(localStorage.getItem("userData") || '{}')
    console.log(this.userData)
    this.ServerAPI.postAPI(this.API.withdrawVirtualInfo, '', (success, data) => {
      if (success && data.code === '0000') {
        this.virtualInfo = data.data
        if (this.virtualInfo.phone) {
          this.columns.push('手机验证')
        }
        if (this.virtualInfo.email) {
          this.columns.push('邮箱验证')
        }
        if (this.virtualInfo.googleKey) {
          this.columns.push('谷歌验证')
        }
      }
    })

  },
  methods: {
    getCode() {
      this.isLoading = true
      this.isSending = true
      let params = {
        validType: this.getVerifyType()
      }
      this.ServerAPI.postAPI(this.API.getCode, params, (success, data) => {
        this.isLoading = false
        if (success) {
          if (data.code === '0000') {
            this.$toastTop('发送成功', 1)
            const TIME_COUNT = 60
            if (!this.timer) {
              this.count = TIME_COUNT
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--
                } else {
                  this.isSending = false
                  clearInterval(this.timer)
                  this.timer = null
                }
              }, 1000)
            }
          } else {
            this.$toastTop(data.info, 3)
            this.isSending = false
          }
        } else {
          this.$toastTop('网络慢，请稍后再试', 2)
          this.isSending = false
        }
      })
    },
    getVerifyType(){
      let validType;
      switch (this.verifyMode) {
        case '手机验证':
          validType = '0'
          break;
        case '邮箱验证':
          validType = '1'
          break;
        case '谷歌验证':
          validType = '2'
          break;
      }
      return validType
    },
    confirm() {
      if (!this.newPassword || !this.confirmPassword || this.newPassword !== this.confirmPassword || this.newPassword.length!==6 || this.confirmPassword.length!==6) {
        this.$toastTop('支付密码格式错误',3)
        return;
      }
      if(this.userData.paypassword && (!this.verifyMode || !this.vCode)) {
        this.$toastTop('请选择验证方式并填写验证码',3)
        return;
      }
      const api = this.userData.paypassword ? this.API.restPayPassword : this.API.savePayPassword
      this.isLoading = true
      this.ServerAPI.postAPI(api, this.userData.paypassword?{
        validType:this.getVerifyType(),
        vcode: this.vCode,
        password: this.newPassword,
      }:{
        password: this.newPassword,
      }, (success, data) => {
        this.isLoading = false
        if (success) {
          if(data.code==='1'){
            this.$toastTop(data.info, 1)
            const userData = JSON.parse(localStorage.getItem("userData"))
            userData.paypassword = true
            localStorage.setItem("userData", JSON.stringify(userData))
            setTimeout(()=>{
              this.$router.back()
            },500)
          }else {
            this.$toastTop(data.info, 3)
          }
        }
      })

    },
  }
}
</script>

<style lang="scss" scoped>
.changeMail {
  .reminds-fonts {
    color: rgb(254, 121, 33);
    margin-top: .2rem;
    padding: 0 .2rem;
  }

  .input-area {
    // width: 94%;
    margin: .3rem auto 0;
    position: relative;

    .input-box {
      // border-bottom: #D7D7D7 1px solid;
    }

    .input-box2 {
      margin-top: .15rem;
      position: relative;

      .code-btn {
        position: absolute;
        bottom: 0;
        right: 0;
        margin: 0 16px 10px 0;
      }
    }

  }
}

.password-error {
  color: red;
  height: .6rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
